﻿CREATE FUNCTION [dbo].[AccountNetwork]
(
	@AccountID int
)
RETURNS nvarchar(10)
AS
BEGIN
	if @AccountID is null
		return null

	declare @CardNumber nvarchar(40), @BankAccountNumber nvarchar(40)
	select @CardNumber = AccountNumber from tblAccount where AccountID = @AccountID

	if LEFT(@CardNumber, 2) in ( '35', '37' )
		return 'AmEx'
	if LEFT(@CardNumber, 4) = '6011' or
		cast(LEFT(@CardNumber, 6) as int) between 622126 and 622925 or
		cast(LEFT(@CardNumber, 3) as int) between 644 and 649 or
		LEFT(@CardNumber, 4) = '65'
		return 'Disc'
	if cast(LEFT(@CardNumber, 6) as int) between 51 and 55
		return 'MC'
	if cast(LEFT(@CardNumber, 6) as int) between 560221 and 560225 or left(@CardNumber, 4) = '5610'
		return 'BC'
	if cast(LEFT(@CardNumber, 6) as int) between 622126 and 622925 or 
		cast(LEFT(@CardNumber, 3) as int) between 624 and 626 or
		CAST(LEFT(@CardNumber, 4) as int) between 6282 and 6288
		return 'CUP'
	if cast(LEFT(@CardNumber, 3) as int) between 300 and 305
		return 'DC-CB'
	if LEFT(@CardNumber, 4) in ( '2014', '2149' )
		return 'DC-eR'
	if LEFT(@CardNumber, 2) = '36'
		return 'DC-Int'
	if LEFT(@CardNumber, 2) in ( '54', '55' )
		return 'DC-UC'
	if cast(LEFT(@CardNumber, 3) as int) between 639 and 637
		return 'IPI'
	if cast(LEFT(@CardNumber, 3) as int) between 3528 and 3589
		return 'JCB'
	if LEFT(@CardNumber, 4) in ( '6304', '6706', '6771', '6709' )
		return 'Lasr'
	if LEFT(@CardNumber, 4) in ( '5018', '5020', '5038', '6304', '6759', '6761', '6763' )
		return 'Maes'
	if LEFT(@CardNumber, 4) in ( '6334', '6767' )
		return 'Solo'
	if LEFT(@CardNumber, 4) in ( '4903', '4905', '4911', '4936', '6333', '6759' ) or
		LEFT(@CardNumber, 6) in ( '564182', '633110' )
		return 'Swch'
	if LEFT(@CardNumber, 1) = '4'
		return 'Visa'
	RETURN 'Unkn'
END